<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { ODropdown, ODropdownItem, OIcon, OTag } from '@opensig/opendesign';
import { NAVS } from '@/config/nav.ts';
import IconOutlink from '~icons/app/icon-outlink.svg';
import { $t } from '@/i18n';
import { useMeetingStore } from '@/stores/meeting';
import { useRoute } from 'vitepress';
import { openWindow } from '@/utils/common.ts';
import { useHeaderStore } from '@/stores/common.ts';
import { getSoftwareList } from '@/api/api-other.ts';
import { storeToRefs } from 'pinia';
// -------------------- hover事件 --------------------
const activeIndex = ref(-1);
const onMouseEnter = (idx: number) => {
  activeIndex.value = idx;
};
const onMouseLeave = () => {
  activeIndex.value = -1;
};
// -------------------- 选中事件 --------------------
const selectedIndex = ref(-1);
const route = useRoute();

const getSelectedIndex = () => {
  const path = route.path.split('/').slice(0, 2).join('/');
  selectedIndex.value = navs.value.findIndex((nav) => {
    return nav.children?.some((item) => {
      return item.href === path;
    });
  });
};

onMounted(() => {
  getSelectedIndex();
});

watch(
  () => route.path,
  () => {
    getSelectedIndex();
  },
);

// -------------------- 过滤NAVS --------------------
const meetingStore = useMeetingStore();
const filterPerm = (navItem: any, permMap: any) => {
  if (navItem.checkPermKey) {
    return permMap[navItem.checkPermKey];
  }
  return true;
};

const navs = computed(() => {
  const path = [] as string[];
  let currentNavs = [];
  const permMap = {
    meeting: meetingStore.hasPerm,
  };
  try {
    currentNavs = NAVS.filter((navItem) => filterPerm(navItem, permMap)).map(function fn(navItem: any) {
      path.push(navItem.label);
      const res = {
        ...navItem,
        _path: [...path],
      };
      if (navItem.children) {
        res.children = navItem.children.filter((navItem) => filterPerm(navItem, permMap)).map(fn);
      }
      path.pop();
      return res;
    });
  } catch {
    currentNavs = NAVS;
  }
  return currentNavs;
});

const jumpToPage = (href: string, target = '_self') => {
  openWindow(href, target);
};

const checkVisible = (date) => {
  if (!date) return true;
  return new Date(date).getTime() >= Date.now();
};

const isHttpUrl = (url: string) => {
  return url?.startsWith('http');
};

const headerStore = useHeaderStore();
const { tagMap } = storeToRefs(headerStore);
const querySoftwareUpdated = () => {
  getSoftwareList()
    .then((res) => {
      const { updateList } = res;
      headerStore.updateTagMap({
        marketplace: updateList?.length > 0 ? 'new' : '',
      });
    });
};

onMounted(() => {
  querySoftwareUpdated();
});
</script>

<template>
  <nav class="header-nav">
    <ul class="nav-list">
      <li
        v-for="(item, idx) in navs"
        :key="item.id"
        :id="item.id"
        class="nav-item"
        :class="{
          'is-selected': selectedIndex === idx,
          'is-active': activeIndex === idx,
        }"
        @mouseenter="onMouseEnter(idx)"
        @mouseleave="onMouseLeave"
      >
        <a class="info-wrap clickable" v-if="!item.children?.length && item.href" @click="jumpToPage(item.href)">
          <span>
            <span>{{ item.label }}</span>
          </span>
        </a>
        <div class="info-wrap" v-else>
          <span>
            <span>{{ item.label }}</span>
          </span>
          <div class="dropdown-wrapper">
            <div class="dropdown-body">
              <div v-for="(childTab, index) in item.children" :key="index" @mouseenter="onMouseEnter(idx)"
                   @mouseleave="onMouseLeave">
                <div class="dropdown-item" v-if="childTab.disabled">
                  <div class="tab-disabled">
                    <span>{{ childTab.label }}</span>
                    <span class="disabled-tag">{{ $t('header.notOnline') }}</span>
                  </div>
                </div>
                <div class="dropdown-item" v-else>
                  <a
                    :href="childTab.href"
                    class="dropdown-link"
                    :target="isHttpUrl(childTab.href) ? '_blank' : '_self'"
                    :rel="isHttpUrl(childTab.href) ? 'noopener noreferrer' : ''"
                  >
                    <span>{{ childTab.label }}</span>
                    <OTag v-if="(tagMap[childTab?.href?.slice(1)] || childTab.tag) && checkVisible(childTab.tagExpire)"
                          color="danger" size="small"
                          round="pill">{{ tagMap[childTab?.href?.slice(1)] || childTab.tag }}
                    </OTag>
                    <OIcon v-if="childTab.jumpOut" class="jump-out-icon">
                      <IconOutlink class="initial-fill" />
                    </OIcon>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </li>
    </ul>
  </nav>
</template>

<style lang="scss" scoped>
.header-nav {
  height: 100%;
}

.nav-list {
  display: flex;
  height: 100%;
  margin-left: var(--o-gap-5);
}

.nav-item {
  position: relative;
  height: 100%;
  @include text1;
  color: var(--o-color-info1);
  pointer-events: auto;
  transition: color var(--o-duration-s) var(--o-easing-standard);

  a {
    color: var(--o-color-info2);
    display: flex;
    align-items: center;
    transition: color var(--o-duration-s) var(--o-easing-standard);
  }

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 16px;
    width: 2em;
    height: 2px;
    border-radius: 2px;
    background-color: var(--o-color-primary1);
    transition: opacity var(--o-duration-m2) var(--o-easing-standard);
    opacity: 0;
  }

  &.is-active,
  &.is-selected {
    color: var(--o-color-primary1);

    &::after {
      opacity: 1;
    }
  }

  &.is-selected,
  &.is-active {
    font-weight: 500;
  }
}

.info-wrap {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 var(--o-gap-4);
  color: var(--o-color-info2);
  word-break: keep-all;
  position: relative;

  &:hover {
    color: var(--o-color-primary1);
  }

  & > span {
    height: 30px;
    display: flex;
    align-items: flex-end;
    @include respond-to('pad_h') {
      height: 28px;
    }
  }

  &.clickable {
    cursor: pointer;
  }

  @include respond-to('pad_h') {
    padding: 0 var(--o-gap-3);
  }

  .dropdown-wrapper {
    position: absolute;
    top: calc(100% - 4px);
    left: 0;
    display: none;
    padding-top: 8px;
    transition: opacity var(--o-duration-s) var(--o-easing-standard);

    .dropdown-body {
      padding: 6px;
      background-color: var(--o-color-control-light);
      box-shadow: var(--o-shadow-2);
      border-radius: var(--o-radius-s);
    }

    .dropdown-item {
      @include text1;
      font-weight: 400;
      white-space: nowrap;
      display: flex;
      align-items: center;
      padding: 6px 12px;
      border-radius: var(--o-radius-s);
      color: var(--o-color-info2);
      background-color: transparent;
      transition: background-color var(--o-duration-s) var(--o-easing-standard);
      cursor: pointer;
      @include hover {
        background-color: var(--o-color-control2-light);
        color: var(--o-color-primary1);
      }
    }

    .dropdown-link {
      color: inherit;
      display: flex;
      align-items: center;
      width: 100%;

      .o-tag {
        margin-left: var(--o-gap-2);
        transform: scale(0.75);
        transform-origin: left center;
      }
    }

    :deep(.jump-out-icon) {
      font-size: 16px;
      margin-left: 4px;

      path {
        fill: currentColor;
        stroke: transparent;
      }

      path[fill='none'] {
        display: none;
      }
    }
  }
}

.nav-item {
  @include hover {
    .dropdown-wrapper {
      display: block;
    }
  }
}

.tab-disabled {
  color: var(--o-color-info4);
  display: flex;
  align-items: center;
  cursor: not-allowed;

  .disabled-tag {
    margin-left: var(--o-gap-1);
    border: 1px solid rgba(224, 226, 230, 1);
    border-radius: var(--o-radius-xs);
    font-size: 10px;
    color: var(--o-color-info3);
    height: 16px;
    width: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>

<style lang="scss">
.navs-dropdown {
  border-radius: 4px;
}
</style>
